<template>
  <Modal :title="$t('sys.authority.authorityManagement')">
    <FosoTabs :tabs-list="tabList" active-name="menu">
      <template #menu>
        <MenuTree
          v-model:menu-half-keys="halfCheckedKeys"
          v-model:menu-ids="menuIds"
        />
      </template>
      <template #apis>
        <ApiTree ref="apiTree" v-model:apichecked-data="apicheckedData" />
      </template>
    </FosoTabs>
  </Modal>
</template>
<script lang="ts" setup>
import type {
  ApiAuthorityItem,
  ApiAuthorityReq,
  MenuAuthorityReq,
} from '#/api/sys/model/authority';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import {
  getAuthorityApiById,
  getAuthorityMenuById,
  updateAuthorityApi,
  updateAuthorityMenu,
} from '#/api/sys/authority';

import ApiTree from './ApiTree.vue';
import MenuTree from './MenuTree.vue';

const tabList = [
  {
    label: $t('sys.authority.menuAuthority'),
    name: 'menu',
  },
  {
    label: $t('sys.authority.apiAuthority'),
    name: 'apis',
  },
];
const apiTree = useTemplateRef('apiTree');
const apicheckedData = ref<ApiAuthorityItem[]>(); // API权限被选择节点数组
const menuIds = ref<number[]>([]); // 菜单被选择节点数组
const halfCheckedKeys = ref<number[]>([]); // 菜单半选节点数组
// api权限更新信息
const apiPostData = ref<ApiAuthorityReq>({});
// 菜单权限更新信息
const menuPostData = ref<MenuAuthorityReq>({});
/**
 * @author Buke
 * @description 更新api权限
 * @returns {void}
 */
const updateApiData = async (): Promise<void> => {
  const res = await apiTree.value?.getApiTreeNodes();
  apiPostData.value.data = res;
  await updateAuthorityApi(apiPostData.value);
};
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    try {
      await updateApiData(); // 更新api权限
      menuPostData.value.menuIds = [
        ...new Set([...halfCheckedKeys.value, ...menuIds.value]),
      ]; // 将选择的节点与半选择的节点的keys合并并且去重！！！
      await updateAuthorityMenu(menuPostData.value); // 更新菜单权限
      ElMessage.success($t('common.operateSuccess'));
      modalApi.close();
    } catch {
      ElMessage.error($t('common.operateFailed'));
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { id } = modalApi.getData();
      apiPostData.value.roleId = id; // apiID
      menuPostData.value.roleId = id; // 菜单ID
      // 获取菜单权限
      const apiSelectoptions = await getAuthorityApiById(id);
      apicheckedData.value = apiSelectoptions.data;
      const menuSelectoptions = await getAuthorityMenuById(id);
      menuIds.value = menuSelectoptions.menuIds;
    }
  },
});
</script>
